﻿using System;
using System.Linq;
using System.Web.Mvc;
using MvcMall.Core.Commands;
using MvcMall.Core.Contacts.Tasks;
using MvcMall.Framework.Mapper;
using SharpArch.Web.NHibernate;
using MvcMall.AdminPortal.Controllers.Article.ViewModels;
using MvcMall.Framework.MvcPager;

namespace MvcMall.AdminPortal.Controllers.Article
{
    public class ArticleController : BaseController
    {
        private readonly IArticleTask _articleTask;
        private readonly IArticleCategoryTask _articleCategoryTask;
        private readonly IMapper<ArticleModel, ArticleCommand> _articleCommandMapper;

        private readonly IMapper<MvcMall.Core.Domains.Article, ArticleModel> _articleModelMapper;



        public ArticleController(IArticleTask articleTask, IArticleCategoryTask articleCategoryTask, IMapper<ArticleModel, ArticleCommand> articleCommandMapper, IMapper<MvcMall.Core.Domains.Article, ArticleModel> articleModelMapper)
        {
            this._articleTask = articleTask;
            this._articleCategoryTask = articleCategoryTask;
            this._articleCommandMapper = articleCommandMapper;
            this._articleModelMapper = articleModelMapper;
        }


        public ActionResult Save(int? menuId)
        {

            ViewData["ArticleCategoryList"] = _articleCategoryTask.GetAll().Select(x => new SelectListItem() { Text = x.CategoryName, Value = x.Id.ToString() });

            if (menuId != null && menuId > 0)
            {
                var articleCategory = _articleTask.Get(Int32.Parse(menuId.ToString()));
                var viewMode = _articleModelMapper.MapFrom(articleCategory);
                if (articleCategory == null)
                    return ShowMsg("不存在该文章");
                return View(viewMode);
            }
            return View();
        }


        [Transaction]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Save(ArticleModel model)
        {

            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var dataModel = _articleCommandMapper.MapFrom(model);
            var demoModle = _articleTask.Save(dataModel);
            return ShowMsg(demoModle != null ? "保存成功" : "保存失败", Url.Action("Index", "Article"));
        }


        public ActionResult Index(int? pageIndex, string title)
        {
            const int pageSize = 10;
            var list = _articleTask.GetPagedList(pageIndex ?? 1, pageSize, title);
            var models = list.Select(_articleModelMapper.MapFrom)
                .ToPagedList(pageIndex ?? 1, pageSize, list.TotalItemCount);
            return View(models);
        }
    }
}
